using HDLogCenter.Bll.Services;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Infrastructure.Models.Inputs;
using Microsoft.AspNetCore.Mvc;

namespace HDLogCenter.Controllers
{
    public class LogManagerController : Controller
    {
        private readonly LogService _logService;
        private readonly ProjectConfigService _projectConfigService;

        public LogManagerController(LogService logService, ProjectConfigService projectConfigService)
        {
            _logService = logService;
            _projectConfigService = projectConfigService;
        }

        public async Task<IActionResult> Index(SearchLogsInput input)
        {
            const int pageSize = 50;
            var searchResult = await _logService.SearchLogsAsync(input);
            var projects = await _projectConfigService.GetAllProjectsAsync();
            //var serverCodes = await _logService.GetServerCodesAsync();
            var model = new LogIndexViewModel
            {
                Logs = searchResult.Hits,
                Projects = projects,
                Code = input.AppCode,
                Level = input.Level,
                StartTime = input.StartTime,
                EndTime = input.EndTime,
                Message = input.Message,
                CurrentPage = input.PageIndex,
                TotalPages = (int)Math.Ceiling((double)searchResult.NbHits/pageSize),
                TotalCount = searchResult.NbHits,
                //ServerCodes = serverCodes
            };

            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Details(long id)
        {
            var log = await _logService.GetLogByIdAsync(id);
            if (log == null)
            {
                return NotFound();
            }

            return View(log);
        }


        [HttpGet]
        public async Task<IActionResult> GetLogs(SearchLogsInput input)
        {
            var searchResult = await _logService.SearchLogsAsync(input);
           
            return Json(new
            {
                code = 0,
                data = searchResult.Hits,
                count = searchResult.Hits.Count(),
                total = searchResult.NbHits,
                page = input.PageIndex,
                pageSize = input.PageSize
            });
        }
    }


}
